#include "maze_map2.h"

#include <iostream>
#include <iomanip>

using namespace std;

mazeMap::mazeMap(std::vector<std::vector<int>> map, int inputX, int inputY, int outputX, int outputY, int mBarrierValue, int roleValue)
	:mMapArray(map),
	mInputX(inputX),
	mInputY(inputY),
	mOutputX(outputX),
	mOutputY(outputY),
	mBarrier(mBarrierValue),
	mRole(roleValue)
{
	//todo something.
}

mazeMap::~mazeMap()
{
	//todo something.
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////

void mazeMap::showArray(std::vector<std::vector<int>>& map)
{
	for (size_t i = 0; i < map.size(); i++)
	{
		for (size_t j = 0; j < map[i].size(); j++)
		{
			cout << setfill(' ') << setw(4) << (map[i][j]);
		}
		cout << endl << endl;

	}
	cout << endl;
}

void mazeMap::showMap()
{
	showArray(mMapArray);
}

std::vector<std::vector<int>> mazeMap::cloneMapArray()
{
	return mMapArray;
}

void mazeMap::calcCoordinate(std::vector<std::vector<int>>& map, int direction, int* x, int* y)
{
	int mazeRow = (int)map.size();
	int mazeColumn = (int)map[0].size();

	switch (direction)
	{
	case MV2_Up:// up
		if (((*y - 1) >= 0) && (map[*y - 1][*x] != mBarrier))
		{
			(*y)--;
		}
		break;
	case MV2_Down: //down
		if (((*y + 1) < mazeRow) && (map[*y + 1][*x] != mBarrier))
		{
			(*y)++;
		}
		break;
	case MV2_Left: //left
		if (((*x - 1) >= 0) && (map[*y][*x - 1] != mBarrier))
		{
			(*x)--;
		}
		break;
	case MV2_Right://right
		if (((*x + 1) < mazeColumn) && (map[*y][*x + 1] != mBarrier))
		{
			(*x)++;
		}
		break;
	default:
		//printf("unsupported this command:%c\n", direction);
		break;
	}
}

void mazeMap::testRun(std::vector<int>& moveSteps, int *endX, int* endY)
{
	int posX = mInputX;
	int posY = mInputY;

	for (size_t i = 0; i < moveSteps.size(); i++)
	{
		calcCoordinate(mMapArray, moveSteps[i], &posX, &posY);
	}

	*endX = posX;
	*endY = posY;
}

void mazeMap::run(std::vector<int>& moveSteps)
{
	int posX = mInputX;
	int posY = mInputY;
	int role = mRole;
	int lastX = posX;
	int lastY = posY;
	vector<vector<int>> goMap = mMapArray;

	for (size_t i = 0; i < moveSteps.size(); i++)
	{
		calcCoordinate(mMapArray, moveSteps[i], &posX, &posY);

		if ((lastX != posX) || (lastY != posY))
		{
			role++;
		}

		//if (goMap[posY][posX] == 0)
		{
			goMap[posY][posX] = role;
		}
		lastX = posX;
		lastY = posY;

		if ((posX == mOutputX) && (posY == mOutputY))
		{
			printf("route maze cost step: %d\n", (int)i);
			showArray(goMap);
			break;
		}
	}
}